package com.kexinde.wjifen.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ValidateCode {

	public Image image;
	public String code = "";
	
	private static final String CHARARRAY[] = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i",
			"j", "k", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
			"x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
			"K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
			"Y", "Z" };

	public ValidateCode(int width, int height, int number){
		this.image = new BufferedImage(width, height, 1);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200,255));
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Arial", 0 ,(width/number+4)));
		g.setColor(getRandColor(160, 200));
		this.code = "";
		for(int i = 0; i < number; i++){
			String rand = getRandChar(random.nextInt(60));
			code += rand;
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110),20 + random.nextInt(110)));
			g.drawString(rand, (width/number - 2) * i + 6, height-4);
		}
		g.dispose();
	}
	
	private String getRandChar(int randNumber) {
		return CHARARRAY[randNumber % CHARARRAY.length];
	}
	
	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255) {
			fc = 255;
		}
		if (bc > 255) {
			bc = 255;
		}
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, b, g);
	}
	
	public Image getImage(){
		return image;
	}
	
	public String getCode(){
		return code;
	}
}
